A tap on your iPhone starts a focus session on this Mac, and a widget on the phone shows whether the Mac is locked and until when. It takes about 20 minutes to set up, once. You need a free Cloudflare account; the widget uses Scriptable, a free app from the App Store.
How it works: the phone leaves "start, 50 minutes" with a small relay that you host on Cloudflare. FocusLock on the Mac keeps asking that relay and starts within a second or two, and tells it what to show on the phone. From the phone you can start a session, add time to one, or use the day's 3-minute pause. Nothing on the phone can end or shorten a session. Cloudflare sees when you tap and for how many minutes, whether the Mac is locked and until when, the name of a place that is holding a session, and both devices' internet addresses. It sees nothing about what you block or browse.
focuslock-relay → Deploy.focuslock.focuslock-relay Worker → Bindings → Add binding → D1 database. Variable name: DB. Database: focuslock.TOKEN. For the value, open FocusLock → the phone button → press Copy, and paste.focuslock-relay.yourname.workers.dev) and paste it into the Relay box in FocusLock. Switch the toggle on. It should say Listening.Cloudflare moves its menus around now and then, so a name may differ slightly from these steps. If it says Refused, the secret in step 5 doesn't match the one in FocusLock: paste it again.
Made your relay before FocusLock 1.3.6? Do step 6 once more with the script below. The widget, Add and Pause need the new script. Everything you already set up, the Shortcut included, keeps working.
// FocusLock relay (Cloudflare Worker). Bindings: DB = D1 database, TOKEN = secret.
// The phone can ask the Mac to start a session, add time to one, or use the day's pause, and
// can read what the Mac last reported. Nothing here can end or shorten a session.
const TTL_MIN = 15; // an unclaimed start request expires after this many minutes
const CMD_TTL_S = 120; // an unclaimed "add time" or "pause" expires much sooner: late, it would be a surprise
const MAX_MIN = 240; // longest session (or addition) the relay will pass on
const TABLES = [
"CREATE TABLE IF NOT EXISTS req (k INTEGER PRIMARY KEY CHECK (k = 1), id TEXT, minutes INTEGER, created INTEGER, state TEXT, ends INTEGER)",
"CREATE TABLE IF NOT EXISTS cmd (k INTEGER PRIMARY KEY CHECK (k = 1), id TEXT, action TEXT, minutes INTEGER, created INTEGER, state TEXT, note TEXT)",
"CREATE TABLE IF NOT EXISTS mac (k INTEGER PRIMARY KEY CHECK (k = 1), state TEXT, at INTEGER, seen INTEGER)",
];
let ready = false; // the tables exist (checked once each time Cloudflare starts this script)
export default {
async fetch(req, env) {
if (!(await authed(req, env.TOKEN))) return json({ error: "unauthorized" }, 401);
const { pathname, searchParams } = new URL(req.url);
if (!ready) { await env.DB.batch(TABLES.map((q) => env.DB.prepare(q))); ready = true; }
// iPhone: request a session. A new tap replaces any older unclaimed request.
if (req.method === "POST" && pathname === "/start") {
const body = await req.json().catch(() => ({}));
const minutes = Math.round(Number(body.minutes));
if (!(minutes >= 1 && minutes <= MAX_MIN)) return json({ error: "minutes must be 1-" + MAX_MIN }, 400);
const id = crypto.randomUUID();
await env.DB.prepare("INSERT OR REPLACE INTO req (k, id, minutes, created, state, ends) VALUES (1, ?, ?, ?, 'pending', NULL)").bind(id, minutes, Date.now()).run();
return json({ ok: true, id, minutes });
}
// iPhone: something to do to a running session. { action: "extend", minutes } or { action: "pause" }.
if (req.method === "POST" && pathname === "/do") {
const body = await req.json().catch(() => ({}));
const action = String(body.action || "");
if (action !== "extend" && action !== "pause") return json({ error: "action must be extend or pause" }, 400);
const minutes = action === "extend" ? Math.round(Number(body.minutes)) : 0;
if (action === "extend" && !(minutes >= 1 && minutes <= MAX_MIN)) return json({ error: "minutes must be 1-" + MAX_MIN }, 400);
const id = crypto.randomUUID();
await env.DB.prepare("INSERT OR REPLACE INTO cmd (k, id, action, minutes, created, state, note) VALUES (1, ?, ?, ?, ?, 'pending', NULL)")
.bind(id, action, minutes, Date.now()).run();
return json({ ok: true, id, action, minutes });
}
// Mac: GET /poll?wait=25 holds the request open up to 25 s and answers as soon as a start is pending.
// With v=2 (FocusLock 1.3.6 and later) it also hands over a pending "extend" or "pause", and notes that the Mac is awake.
if (req.method === "GET" && pathname === "/poll") {
const wait = Math.min(25, Math.max(0, Number(searchParams.get("wait")) || 0));
const v2 = searchParams.get("v") === "2";
const deadline = Date.now() + wait * 1000;
if (v2) await env.DB.prepare("INSERT INTO mac (k, seen) VALUES (1, ?) ON CONFLICT(k) DO UPDATE SET seen = excluded.seen").bind(Date.now()).run();
for (;;) {
const row = await pending(env);
const command = v2 ? await pendingCommand(env) : null;
if (row || command || Date.now() >= deadline) return json(v2 ? { pending: row, command } : { pending: row });
await new Promise((r) => setTimeout(r, 1000));
}
}
// Mac: after the daemon has really started the session. Consumes the request exactly once.
if (req.method === "POST" && pathname === "/ack") {
const body = await req.json().catch(() => ({}));
const r = await env.DB.prepare("UPDATE req SET state = 'locked', ends = ? WHERE k = 1 AND id = ? AND state = 'pending'")
.bind(Number(body.ends) || null, String(body.id)).run();
return json({ ok: true, consumed: r.meta.changes === 1 });
}
// Mac: how an "extend" or "pause" went. Consumes it exactly once.
if (req.method === "POST" && pathname === "/done") {
const body = await req.json().catch(() => ({}));
const r = await env.DB.prepare("UPDATE cmd SET state = ?, note = ? WHERE k = 1 AND id = ? AND state = 'pending'")
.bind(body.ok ? "done" : "refused", String(body.note || "").slice(0, 200), String(body.id)).run();
return json({ ok: true, consumed: r.meta.changes === 1 });
}
// Mac: what to show on the phone (locked or not, until when). Kept as it was sent.
if (req.method === "POST" && pathname === "/state") {
const body = await req.json().catch(() => null);
const text = body && typeof body === "object" && !Array.isArray(body) ? JSON.stringify(body) : "";
if (!text || text.length > 2000) return json({ error: "state must be a small JSON object" }, 400);
const now = Date.now();
await env.DB.prepare("INSERT INTO mac (k, state, at, seen) VALUES (1, ?, ?, ?) ON CONFLICT(k) DO UPDATE SET state = excluded.state, at = excluded.at, seen = excluded.seen")
.bind(text, now, now).run();
return json({ ok: true });
}
// iPhone: what is going on. request = the last start asked for ("pending" or "locked"; ends is a Unix time in ms).
// command = the last extend or pause ("pending", "done", "refused" or "expired"). mac = what the Mac last reported,
// with at (when) and seen (when the Mac last checked in). now = this relay's clock, to judge those against.
if (req.method === "GET" && pathname === "/status") {
const now = Date.now();
const row = await env.DB.prepare("SELECT id, minutes, created, state, ends FROM req WHERE k = 1").first().catch(() => null);
const command = await env.DB.prepare("SELECT id, action, minutes, created, state, note FROM cmd WHERE k = 1").first().catch(() => null);
if (command && command.state === "pending" && command.created <= now - CMD_TTL_S * 1000) command.state = "expired";
const m = await env.DB.prepare("SELECT state, at, seen FROM mac WHERE k = 1").first().catch(() => null);
let mac = null;
if (m) { try { mac = { ...JSON.parse(m.state || "{}"), at: m.at, seen: m.seen }; } catch { mac = { at: m.at, seen: m.seen }; } }
return json({ request: row, command, mac, now });
}
return json({ error: "not found" }, 404);
},
};
async function pending(env) {
try {
return await env.DB.prepare("SELECT id, minutes, created FROM req WHERE k = 1 AND state = 'pending' AND created > ?")
.bind(Date.now() - TTL_MIN * 60000).first();
} catch {
return null;
}
}
async function pendingCommand(env) {
try {
return await env.DB.prepare("SELECT id, action, minutes, created FROM cmd WHERE k = 1 AND state = 'pending' AND created > ?")
.bind(Date.now() - CMD_TTL_S * 1000).first();
} catch {
return null;
}
}
async function authed(req, token) {
const given = (req.headers.get("Authorization") || "").replace(/^Bearer /, "");
if (!token || !given) return false;
const enc = new TextEncoder();
const [a, b] = await Promise.all([given, token].map((s) => crypto.subtle.digest("SHA-256", enc.encode(s))));
const x = new Uint8Array(a), y = new Uint8Array(b);
let diff = 0;
for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i];
return diff === 0;
}
function json(obj, status = 200) {
return new Response(JSON.stringify(obj), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
}
The widget says Locked with a clock counting down to the end, Unlocked with the next scheduled lock, or Paused. Tap it for the menu: Lock 25, 50 or 90 min when the Mac is open; Add 15 or 30 min and Pause 3 min when it's locked.
iOS decides when a widget is redrawn, usually every few minutes, so a change on the Mac can take a little while to appear. The countdown itself runs on its own, and the menu always asks the relay afresh.
// FocusLock for iPhone. A widget for the Scriptable app: it shows what FocusLock on your Mac
// is doing, and a tap opens a short menu to lock the Mac, add time, or use the day's pause.
// It can't end or shorten a session; nothing on the phone can.
//
// Set up: run this once in Scriptable. It asks for your relay's address and the secret
// (FocusLock on the Mac, the phone button, Copy). Both are kept in the iPhone's keychain.
const STARTS = [25, 50, 90]; // minutes offered when the Mac isn't locked
const ADDS = [15, 30]; // minutes offered when it is
const AWAKE_MS = 150000; // the Mac checks in every 25 s; quiet for this long means asleep or offline
const K_URL = "focuslock.relay", K_SECRET = "focuslock.secret";
const ACCENT = new Color("#fa2e4a"), QUIET = new Color("#8e8e93");
// ---- settings
function saved() {
if (!Keychain.contains(K_URL) || !Keychain.contains(K_SECRET)) return null;
return { url: Keychain.get(K_URL), secret: Keychain.get(K_SECRET) };
}
// "focuslock-relay.you.workers.dev/status " -> "https://focuslock-relay.you.workers.dev"
function tidy(url) {
let t = String(url || "").trim();
if (!t) return "";
if (!/^https?:\/\//i.test(t)) t = "https://" + t;
const m = t.match(/^(https?:\/\/[^\/?#\s]+)/i);
return m ? m[1] : "";
}
async function askSettings(old) {
const a = new Alert();
a.title = "FocusLock";
a.message = "Your relay's address, and the secret from FocusLock on the Mac (the phone button, then Copy).";
const field = a.addTextField("focuslock-relay.you.workers.dev", old ? old.url.replace(/^https:\/\//i, "") : "");
if (field && field.setURLKeyboard) field.setURLKeyboard();
a.addSecureTextField(old ? "Secret (leave empty to keep it)" : "Secret", "");
a.addAction("Save");
a.addCancelAction("Cancel");
if ((await a.presentAlert()) < 0) return old;
const url = tidy(a.textFieldValue(0));
const secret = String(a.textFieldValue(1) || "").trim().replace(/^Bearer\s+/i, "") || (old ? old.secret : "");
if (!url || !secret) { await say("Not saved", "Both the address and the secret are needed."); return old; }
Keychain.set(K_URL, url);
Keychain.set(K_SECRET, secret);
return { url, secret };
}
// ---- talking to the relay
async function call(s, method, path, body) {
const r = new Request(s.url + path);
r.method = method;
r.timeoutInterval = 10;
r.headers = { Authorization: "Bearer " + s.secret, "Content-Type": "application/json" };
if (body) r.body = JSON.stringify(body);
const j = await r.loadJSON();
const code = r.response ? r.response.statusCode : 0;
if (code === 401 || code === 403) throw new Error("refused");
if (code !== 200) throw new Error((j && j.error) || "the relay answered " + code);
return j;
}
async function look(s) {
if (!s) return { kind: "setup" };
try { return read(await call(s, "GET", "/status")); }
catch (e) { return { kind: e && e.message === "refused" ? "refused" : "error" }; }
}
function wait(ms) { return new Promise((done) => Timer.schedule(ms, false, done)); }
// ---- what the relay's answer means
function read(j) {
if (!j || !("mac" in j)) return { kind: "old" }; // a relay from before FocusLock 1.3.6
const m = j.mac, now = Date.now();
if (!m || m.active === undefined) return { kind: "never" }; // the Mac hasn't reported yet (an older FocusLock, or switched off)
const awake = !!m.seen && j.now - m.seen < AWAKE_MS;
const canPause = m.pauseAvailable !== false;
// a session whose end has passed is over, even if the Mac was asleep and never said so
const running = m.active === true && (!!m.place || !m.ends || m.ends > now);
if (!running) return { kind: "open", awake, pauseAvailable: canPause, next: m.next && m.next > now ? new Date(m.next) : null };
const paused = m.paused === true && m.pauseEnds > now;
return { kind: paused ? "paused" : "locked", awake, pauseAvailable: canPause, place: m.place || null,
ends: m.ends ? new Date(m.ends) : null, pauseEnds: paused ? new Date(m.pauseEnds) : null };
}
// "4:30 PM" today, "Thu 9:00 AM" this week, "Dec 3" further off
function clock(d) {
const now = new Date();
const time = d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
if (d.toDateString() === now.toDateString()) return time;
if (d - now < 6 * 86400000) return d.toLocaleDateString([], { weekday: "short" }) + " " + time;
return d.toLocaleDateString([], { month: "short", day: "numeric" });
}
// one line that says it all (the Lock Screen's single line, and the menu's title)
function headline(v) {
switch (v.kind) {
case "locked": return v.place ? "Locked at " + v.place : v.ends ? "Locked until " + clock(v.ends) : "Locked";
case "paused": return "Paused until " + clock(v.pauseEnds);
case "open": return v.next ? "Unlocked. Locks " + clock(v.next) : "Unlocked";
case "old": return "Update the relay";
case "never": return "Update FocusLock on the Mac";
case "setup": return "Open to set up";
case "refused": return "The secret doesn't match";
default: return "No connection";
}
}
const TITLES = { locked: "Locked", paused: "Paused", open: "Unlocked", old: "Update relay", never: "Update Mac", setup: "Set up", refused: "Wrong secret", error: "Offline" };
// ---- the widget
function build(v, family) {
const w = new ListWidget();
w.url = URLScheme.forRunningScript(); // a tap runs this script: the menu
const now = new Date(), soon = new Date(now.getTime() + 15 * 60000);
const change = v.kind === "paused" ? v.pauseEnds : v.kind === "locked" ? v.ends : v.next;
w.refreshAfterDate = change && change > now && change < soon ? change : soon; // a hint; iOS decides
const on = v.kind === "locked" || v.kind === "paused";
const symbol = SFSymbol.named(v.kind === "paused" ? "pause.fill" : on ? "lock.fill" : "lock.open.fill");
const title = TITLES[v.kind] || TITLES.error;
const accessory = String(family || "").indexOf("accessory") === 0; // the Lock Screen's sizes
if (family === "accessoryInline") { w.addText(headline(v)); return w; }
if (family === "accessoryCircular") {
w.addAccessoryWidgetBackground = true;
const i = w.addImage(symbol.image);
i.imageSize = new Size(26, 26);
i.centerAlignImage();
return w;
}
if (!accessory) {
w.backgroundColor = new Color("#0c0c0e");
w.setPadding(16, 16, 16, 16);
symbol.applyFont(Font.boldSystemFont(24));
const i = w.addImage(symbol.image);
i.imageSize = new Size(26, 26);
i.tintColor = on ? ACCENT : QUIET;
w.addSpacer(null);
}
const t = w.addText(title);
t.font = Font.boldSystemFont(accessory ? 16 : 22);
if (!accessory) t.textColor = Color.white();
t.lineLimit = 1;
t.minimumScaleFactor = 0.7;
// under the title: a clock that runs by itself, then one quiet line
const big = (x) => { x.font = Font.mediumSystemFont(accessory ? 14 : 17); if (!accessory) x.textColor = Color.white(); x.lineLimit = 1; x.minimumScaleFactor = 0.6; };
const small = (text) => { const x = w.addText(text); x.font = Font.systemFont(accessory ? 12 : 13); if (!accessory) x.textColor = QUIET; x.lineLimit = 1; x.minimumScaleFactor = 0.7; };
if (v.kind === "paused") {
const d = w.addDate(v.pauseEnds); d.applyTimerStyle(); big(d);
if (!accessory) small("Then locked");
} else if (v.kind === "locked" && v.place) {
big(w.addText("Until you leave"));
small(v.place);
} else if (v.kind === "locked" && v.ends) {
const d = w.addDate(v.ends); d.applyTimerStyle(); big(d);
small("Until " + clock(v.ends));
} else if (v.kind === "open") {
if (v.next) small("Locks " + clock(v.next));
if (!v.awake && !(accessory && v.next)) small("Mac offline");
} else if (!accessory) {
small(v.kind === "setup" || v.kind === "refused" ? "Tap to fix" : v.kind === "error" ? "No connection" : "Tap for more");
}
return w;
}
// ---- the menu (a tap on the widget, or running this in Scriptable)
async function say(title, message) {
const a = new Alert();
a.title = title;
if (message) a.message = message;
a.addAction("OK");
await a.presentAlert();
}
async function lock(s, minutes) {
const r = await call(s, "POST", "/start", { minutes });
for (let i = 0; i < 10; i++) {
await wait(1000);
const j = await call(s, "GET", "/status");
if (j.request && j.request.id === r.id && j.request.state === "locked") {
return say("Locked", j.request.ends ? "Until " + clock(new Date(j.request.ends)) + "." : "");
}
}
return say("Not yet", "The Mac hasn't answered. It may be asleep or off. It locks when it wakes, if that's within 15 minutes.");
}
// add time, or the day's pause: the Mac's blocker decides, and says how it went
async function ask(s, body) {
const r = await call(s, "POST", "/do", body);
for (let i = 0; i < 12; i++) {
await wait(1000);
const j = await call(s, "GET", "/status");
const c = j.command;
if (c && c.id === r.id && c.state !== "pending") {
if (c.state === "done") return say(body.action === "pause" ? "Paused" : "Added", headline(read(j)) + ".");
return say("Not done", c.note || "The Mac said no.");
}
}
return say("No answer", "The Mac hasn't answered. It may be asleep or offline. If it wakes within two minutes, this still goes through.");
}
async function otherLength(s) {
const a = new Alert();
a.title = "Lock for how long?";
const f = a.addTextField("Minutes", "");
if (f && f.setNumberPadKeyboard) f.setNumberPadKeyboard();
a.addAction("Lock");
a.addCancelAction("Cancel");
if ((await a.presentAlert()) < 0) return;
const m = Math.round(Number(a.textFieldValue(0)));
if (!(m >= 5 && m <= 240)) return say("Not locked", "From the phone, a session is 5 minutes to 4 hours.");
return lock(s, m);
}
async function pause(s) {
const a = new Alert();
a.title = "Use today's pause?";
a.message = "Everything opens for 3 minutes. Once a day, and the session's clock keeps running.";
a.addAction("Pause");
a.addCancelAction("Cancel");
if ((await a.presentAlert()) < 0) return;
return ask(s, { action: "pause" });
}
async function menu(s) {
if (!s) { s = await askSettings(null); if (!s) return; }
const v = await look(s);
const a = new Alert();
a.title = headline(v);
if (v.kind === "open" && !v.awake) a.message = "The Mac is asleep or offline. A lock you ask for now starts when it wakes, if that's within 15 minutes.";
if (v.kind === "old") a.message = "The relay is from before FocusLock 1.3.6. Replace its script with the one in FocusLock's phone guide to see the Mac here.";
if (v.kind === "never") a.message = "The relay hasn't heard from the Mac. Update FocusLock there, and check the phone switch is on.";
if (v.kind === "refused") a.message = "Copy the secret from FocusLock on the Mac again, and paste it in Settings.";
const todo = [];
const add = (title, run) => { a.addAction(title); todo.push(run); };
if (v.kind === "open" || v.kind === "old" || v.kind === "never") {
for (const m of STARTS) add("Lock " + m + " min", () => lock(s, m));
add("Other", () => otherLength(s));
}
if (v.kind === "locked" && !v.place) for (const m of ADDS) add("Add " + m + " min", () => ask(s, { action: "extend", minutes: m }));
if (v.kind === "locked" && v.pauseAvailable) add("Pause 3 min", () => pause(s));
add("Settings", () => askSettings(s));
a.addCancelAction("Close");
const i = await a.presentSheet();
if (i < 0 || !todo[i]) return;
try { await todo[i](); }
catch (e) { await say("Not done", e && e.message === "refused" ? "The secret doesn't match." : "The relay couldn't be reached."); }
}
// ---- run
if (config.runsInWidget) Script.setWidget(build(await look(saved()), config.widgetFamily));
else await menu(saved());
Script.complete();
A Shortcut can only start a session, but it works from the Action Button and from Siri.
https://focuslock-relay.yourname.workers.dev/start (your Worker's address, then /start)Authorization, value Bearer followed by the secret (the word Bearer, a space, then the secret from FocusLock's Copy button). The easy way to get the secret onto the phone is to copy it on the Mac and paste on the iPhone with Universal Clipboard.minutes, type Number, value: the number from step 2.